package com.dsz.apibackend.controller;

import com.dsz.apibackend.common.BaseResponse;
import com.dsz.apibackend.common.ErrorCode;
import com.dsz.apibackend.common.ResultUtils;
import com.dsz.apibackend.exception.BusinessException;
import com.dsz.apibackend.mapper.InterfaceInfoMapper;
import com.dsz.apibackend.model.domain.UserInterfaceInfo;
import com.dsz.apibackend.model.vo.InterfaceInfoVO;
import com.dsz.apibackend.service.InterfaceInfoService;
import com.dsz.apicommon.model.domain.InterfaceInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/analysis")
public class AnalysisController {
    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;

    /**
     * 获取接口调用次数的统计信息，取调用次数最多的前三个接口
     */
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfoVO>> listInterfaceInfoVO(HttpServletRequest request) {
        //校验参数
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断是否为管理员
        if (!interfaceInfoService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //查询数据库
        List<UserInterfaceInfo> userInterfaceInfoList = interfaceInfoMapper.listInterfaceInfoVO(3);
        if (userInterfaceInfoList == null || userInterfaceInfoList.size() == 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "无接口");
        }
        //将数据转换为InterfaceInfoVO
        List<InterfaceInfoVO> interfaceInfoVOList = userInterfaceInfoList.stream().map(item -> {
            InterfaceInfo interfaceInfo = interfaceInfoService.getById(item.getInterfaceInfoId());
            InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);
            interfaceInfoVO.setTotalNum(item.getTotalNum());
            return interfaceInfoVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(interfaceInfoVOList);
    }
}
